class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        return self.recur(preorder, inorder)

    def recur(self, preorder, inorder):
        if not inorder:
            return None

        root_val = preorder.pop(0)
        root = TreeNode(root_val)
        root_index = inorder.index(root_val)

        root.left = self.recur(preorder, inorder[:root_index])
        root.right = self.recur(preorder, inorder[root_index + 1:])

        return root